#!/bin/bash

# QEMU K8s一主二备拓扑部署脚本
# 自动创建1个master节点和2个worker节点

set -e

# 加载配置文件
SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SOURCE_DIR/config.conf"

# 颜色输出函数
red() { echo -e "\033[31m$1\033[0m"; }
green() { echo -e "\033[32m$1\033[0m"; }
yellow() { echo -e "\033[33m$1\033[0m"; }
blue() { echo -e "\033[34m$1\033[0m"; }

echo "$(blue '=== QEMU K8s一主二备拓扑部署 ===')"
echo

# 检查必要文件
if [ ! -f "$SOURCE_DIR/create-vm.sh" ]; then
    echo "$(red '错误: create-vm.sh 脚本不存在')"
    exit 1
fi

if [ ! -f "$SOURCE_DIR/setup-network.sh" ]; then
    echo "$(red '错误: setup-network.sh 脚本不存在')"
    exit 1
fi

# 检查ISO文件
if [ ! -f "$ISO_PATH" ]; then
    echo "$(red "错误: ISO文件不存在: $ISO_PATH")"
    echo "请检查config.conf中的ISO_PATH配置"
    exit 1
fi

# 定义节点信息
declare -A NODES
NODES["${VM_NAME_PREFIX}-master1"]="master:$MASTER1_IP"
NODES["${VM_NAME_PREFIX}-worker1"]="worker:$WORKER1_IP"
NODES["${VM_NAME_PREFIX}-worker2"]="worker:$WORKER2_IP"

echo "$(yellow '部署配置:')"
echo "拓扑类型: 一主二备 (1 Master + 2 Workers)"
echo "虚拟机前缀: $VM_NAME_PREFIX"
echo "网络子网: $NETWORK_SUBNET"
echo "ISO镜像: $ISO_PATH"
echo

echo "$(yellow '节点列表:')"
for vm_name in "${!NODES[@]}"; do
    IFS=':' read -r vm_type vm_ip <<< "${NODES[$vm_name]}"
    printf "%-20s %-10s %s\n" "$vm_name" "$vm_type" "$vm_ip"
done
echo

# 确认部署
read -p "是否继续部署? (y/N): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "$(yellow '部署已取消')"
    exit 0
fi

# 检查网络配置
echo "$(blue '检查网络配置...')"
if ! ip link show "$BRIDGE_NAME" >/dev/null 2>&1; then
    echo "$(yellow "网桥 $BRIDGE_NAME 不存在，正在配置网络...")"
    if [ "$EUID" -ne 0 ]; then
        echo "$(red '需要root权限配置网络，请运行:')"
        echo "sudo $SOURCE_DIR/setup-network.sh"
        exit 1
    else
        "$SOURCE_DIR/setup-network.sh"
    fi
else
    echo "$(green "✓ 网桥 $BRIDGE_NAME 已存在")"
fi
echo

# 创建虚拟机
echo "$(blue '开始创建虚拟机...')"
echo

for vm_name in "${!NODES[@]}"; do
    IFS=':' read -r vm_type vm_ip <<< "${NODES[$vm_name]}"
    
    echo "$(yellow "创建虚拟机: $vm_name")"
    echo "类型: $vm_type, IP: $vm_ip"
    
    if "$SOURCE_DIR/create-vm.sh" "$vm_name" "$vm_type" "$vm_ip"; then
        echo "$(green "✓ $vm_name 创建成功")"
    else
        echo "$(red "✗ $vm_name 创建失败")"
        exit 1
    fi
    echo
done

# 创建批量操作脚本
echo "$(blue '创建批量操作脚本...')"

# 批量安装脚本
INSTALL_ALL_SCRIPT="$SOURCE_DIR/install-all-1m2w.sh"
cat > "$INSTALL_ALL_SCRIPT" << 'EOF'
#!/bin/bash

# 批量启动一主二备拓扑的安装模式

set -e

SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SOURCE_DIR/config.conf"

echo "启动一主二备拓扑安装模式..."
echo

# 定义节点
NODES=("${VM_NAME_PREFIX}-master1" "${VM_NAME_PREFIX}-worker1" "${VM_NAME_PREFIX}-worker2")

for vm_name in "${NODES[@]}"; do
    install_script="$VM_IMAGE_DIR/install-${vm_name}.sh"
    if [ -f "$install_script" ]; then
        echo "启动 $vm_name 安装模式..."
        "$install_script"
        echo "$vm_name 安装模式已启动"
    else
        echo "警告: $install_script 不存在"
    fi
    echo
done

echo "所有虚拟机安装模式已启动"
echo "请通过VNC客户端连接各虚拟机完成系统安装:"
echo
for vm_name in "${NODES[@]}"; do
    info_file="$VM_IMAGE_DIR/${vm_name}.info"
    if [ -f "$info_file" ]; then
        vnc_port=$(grep "VNC_PORT=" "$info_file" | cut -d'=' -f2)
        echo "$vm_name: VNC端口 $vnc_port (localhost:$vnc_port)"
    fi
done
EOF

chmod +x "$INSTALL_ALL_SCRIPT"

# 批量启动脚本
START_ALL_SCRIPT="$SOURCE_DIR/start-all-1m2w.sh"
cat > "$START_ALL_SCRIPT" << 'EOF'
#!/bin/bash

# 批量启动一主二备拓扑的所有虚拟机

set -e

SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SOURCE_DIR/config.conf"

echo "启动一主二备拓扑所有虚拟机..."
echo

# 定义节点启动顺序（先启动master）
NODES=("${VM_NAME_PREFIX}-master1" "${VM_NAME_PREFIX}-worker1" "${VM_NAME_PREFIX}-worker2")

for vm_name in "${NODES[@]}"; do
    start_script="$VM_IMAGE_DIR/start-${vm_name}.sh"
    if [ -f "$start_script" ]; then
        echo "启动 $vm_name..."
        "$start_script"
        sleep 2  # 等待2秒再启动下一个
    else
        echo "警告: $start_script 不存在"
    fi
done

echo
echo "所有虚拟机已启动"
echo "虚拟机状态:"
for vm_name in "${NODES[@]}"; do
    pid_file="$VM_IMAGE_DIR/${vm_name}.pid"
    if [ -f "$pid_file" ] && kill -0 "$(cat "$pid_file")" 2>/dev/null; then
        echo "✓ $vm_name: 运行中"
    else
        echo "✗ $vm_name: 未运行"
    fi
done
EOF

chmod +x "$START_ALL_SCRIPT"

# 批量停止脚本
STOP_ALL_SCRIPT="$SOURCE_DIR/stop-all-1m2w.sh"
cat > "$STOP_ALL_SCRIPT" << 'EOF'
#!/bin/bash

# 批量停止一主二备拓扑的所有虚拟机

set -e

SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SOURCE_DIR/config.conf"

echo "停止一主二备拓扑所有虚拟机..."
echo

# 定义节点（逆序停止，先停worker）
NODES=("${VM_NAME_PREFIX}-worker2" "${VM_NAME_PREFIX}-worker1" "${VM_NAME_PREFIX}-master1")

for vm_name in "${NODES[@]}"; do
    pid_file="$VM_IMAGE_DIR/${vm_name}.pid"
    monitor_file="$VM_IMAGE_DIR/${vm_name}.monitor"
    
    if [ -f "$pid_file" ]; then
        pid=$(cat "$pid_file")
        if kill -0 "$pid" 2>/dev/null; then
            echo "停止 $vm_name (PID: $pid)..."
            # 尝试优雅关机
            if [ -S "$monitor_file" ]; then
                echo "system_powerdown" | socat - "$monitor_file" 2>/dev/null || true
                sleep 3
            fi
            # 如果还在运行，强制终止
            if kill -0 "$pid" 2>/dev/null; then
                kill "$pid" 2>/dev/null || true
                sleep 1
            fi
            rm -f "$pid_file"
            echo "✓ $vm_name 已停止"
        else
            echo "$vm_name 未运行"
            rm -f "$pid_file"
        fi
    else
        echo "$vm_name PID文件不存在"
    fi
done

echo
echo "所有虚拟机已停止"
EOF

chmod +x "$STOP_ALL_SCRIPT"

# 状态检查脚本
STATUS_SCRIPT="$SOURCE_DIR/status-1m2w.sh"
cat > "$STATUS_SCRIPT" << 'EOF'
#!/bin/bash

# 一主二备拓扑状态检查脚本

SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SOURCE_DIR/config.conf"

echo "=== 一主二备拓扑状态 ==="
echo

# 定义节点
NODES=("${VM_NAME_PREFIX}-master1" "${VM_NAME_PREFIX}-worker1" "${VM_NAME_PREFIX}-worker2")

echo "虚拟机状态:"
printf "%-20s %-10s %-15s %-10s %s\n" "虚拟机名称" "类型" "IP地址" "状态" "VNC端口"
echo "------------------------------------------------------------"

for vm_name in "${NODES[@]}"; do
    info_file="$VM_IMAGE_DIR/${vm_name}.info"
    pid_file="$VM_IMAGE_DIR/${vm_name}.pid"
    
    if [ -f "$info_file" ]; then
        vm_type=$(grep "VM_TYPE=" "$info_file" | cut -d'=' -f2)
        vm_ip=$(grep "VM_IP=" "$info_file" | cut -d'=' -f2)
        vnc_port=$(grep "VNC_PORT=" "$info_file" | cut -d'=' -f2)
        
        if [ -f "$pid_file" ] && kill -0 "$(cat "$pid_file")" 2>/dev/null; then
            status="运行中"
        else
            status="已停止"
        fi
        
        printf "%-20s %-10s %-15s %-10s %s\n" "$vm_name" "$vm_type" "$vm_ip" "$status" "$vnc_port"
    else
        printf "%-20s %-10s %-15s %-10s %s\n" "$vm_name" "未知" "未知" "未创建" "未知"
    fi
done

echo
echo "网络状态:"
if ip link show "$BRIDGE_NAME" >/dev/null 2>&1; then
    echo "✓ 网桥 $BRIDGE_NAME 已配置"
    ip addr show "$BRIDGE_NAME" | grep inet | head -1
else
    echo "✗ 网桥 $BRIDGE_NAME 未配置"
fi

echo
echo "可用操作:"
echo "- 批量安装: $SOURCE_DIR/install-all-1m2w.sh"
echo "- 批量启动: $SOURCE_DIR/start-all-1m2w.sh"
echo "- 批量停止: $SOURCE_DIR/stop-all-1m2w.sh"
echo "- 状态检查: $SOURCE_DIR/status-1m2w.sh"
EOF

chmod +x "$STATUS_SCRIPT"

echo "$(green '一主二备拓扑部署完成!')"
echo
echo "$(yellow '创建的虚拟机:')"
for vm_name in "${!NODES[@]}"; do
    IFS=':' read -r vm_type vm_ip <<< "${NODES[$vm_name]}"
    echo "- $vm_name ($vm_type): $vm_ip"
done
echo

echo "$(yellow '批量操作脚本:')"
echo "- 批量安装: $INSTALL_ALL_SCRIPT"
echo "- 批量启动: $START_ALL_SCRIPT"
echo "- 批量停止: $STOP_ALL_SCRIPT"
echo "- 状态检查: $STATUS_SCRIPT"
echo

echo "$(blue '下一步操作:')"
echo "1. 运行批量安装: $INSTALL_ALL_SCRIPT"
echo "2. 通过VNC连接各虚拟机完成CentOS安装"
echo "3. 安装完成后运行: $START_ALL_SCRIPT"
echo "4. 检查状态: $STATUS_SCRIPT"
echo

echo "$(green '部署完成! 现在可以开始安装虚拟机系统了。')"